package utility
import(
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"
)

func writeErr(err error){
	if err!=nil{
		log.Println(err)
	}
}

func back_run(logFile string)(*exec.Cmd,error){
	envName := "XD_DAEMON"
	envValue:= "SUB_PROC"

	val := os.Getenv(envName)
	if val == envValue{
		return nil,nil
	}
	cmd := &exec.Cmd{
		Path : os.Args[0],
		Args : os.Args,
		Env  : os.Environ(),
	}
	cmd.Env = append(cmd.Env,fmt.Sprintf("%s=%s",envName,envValue))
	if logFile != "" {
		stdout,err := os.OpenFile(logFile,os.O_CREATE|os.O_RDWR,666)
		writeErr(err)
		cmd.Stderr = stdout
		cmd.Stdout = stdout
	}

	err := cmd.Start()
	if err!=nil{
		return nil,err
	}
	return cmd,err
}

func TestProcess(){
	cmd,err:=back_run("./work-mgr/logs.log")
	if err!=nil{
		log.Fatal("run fail:\n",err)
	}
	if(cmd!=nil){
		log.Fatal("parent process\n")
	}else{
		log.Fatal("sub process\n")
	}
}

func LinuxExists(appName string) bool{
    cmd := exec.Command("ps","-C",appName)
	output,_ := cmd.Output()
    	ret := false
	fields := strings.Fields(string(output))
	for _,v := range fields{
		if v==appName{
			ret = true
			break
		}
	}
	return ret
}

func WindowsExist(appName string) bool{
    cmd := exec.Command("cmd","/C","tasklist")
	output,_ := cmd.Output()
    ret := false
	fields := strings.Fields(string(output))
	//log.Println(string(output))
	for _,v := range fields{
		if v==appName{
			ret = true
			break
		}
	}
	return ret
}

func IsProcessExists(appName string) bool{
	ret := false
	if(runtime.GOOS=="windows"){
        ret = WindowsExist(appName)
    }else{
        ret = LinuxExists(appName)
    }
	return ret
}

func CheckAndRun(path string,name string){
	exec_name := path+name
	log.Println("CheckAndRun:",exec_name)
	if !IsProcessExists(name){
		log.Println("1111111111111111111:",exec_name)
		go execProcess(exec_name)
	}else{
		log.Println("2222222222222222222:",exec_name)
		KillProcess(name)
	}
}

func KillInWindows(appName string){
	log.Println("KillInWindows process exists:",appName)
    cmd := exec.Command("taskkill.exe","/F","/IM",appName)
    err := cmd.Start()
	if err !=nil {
		log.Println("kill error:",err)
	}
	output,_ := cmd.Output()
	log.Println(string(output))
    writeErr(err)
    cmd.Wait()
}

func KillInLinux(appName string){
    log.Println("KillInLinux process exists:",appName)
    cmd := exec.Command("pkill","-9",appName)
    err := cmd.Start()
    writeErr(err)
    cmd.Wait()
}

func KillProcess(name string){
	if IsProcessExists(name){
        if(runtime.GOOS=="windows"){
            go KillInWindows(name)
        }else{
            //go KillInLinux(name)
        }
	}
}

func execProcess(appName string){
	cmd := exec.Command(appName)
	cmd.Output()
}
